import React from 'react';
import ReactDOM from 'react-dom';
import Helmet from 'react-helmet';
import { connect } from 'react-redux';
import { createForm } from 'rc-form';
import { NavBar, Icon, Tabs, WhiteSpace, SegmentedControl, Picker, List, PullToRefresh, Toast, InputItem } from 'antd-mobile';

import RadioBox from '../../components/common/RadioBox';
import Drawer from '../../components/common/Drawer';
import Modal from '../../components/common/Modal';
import Loading from '../../components/common/Loading';
import Select from '../../components/common/Select';
import Star from '../../components/common/Star';
import CList from '../../components/Customer/CustomerList';
import AddCustomer from '../../components/Customer/AddCustomer';

import {getNotEmptyObj, getLabelValueData} from '../../utils/crmUtils';

import {withClient} from '../../hoc';

import './index.sass';

@withClient
@createForm()
@connect((state) => ({access_token: state.token.access_token}))
export default class CustomerList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tabs: [{ title: '未签约客户', value: 1 }, { title: '已签约客户', value: 2 }],
      sign: false,
      isTeam: 0,
      hasTeam: false,
      open: false,
      height: 0,

      pageSize: 1,
      total: 1,
      searchPageSize: 1,
      searchTotal: 1,
      customerData: [],
      sales: [],
      saleId: '',
      sidebar:null,
      
      searchCustomerData: [],
      searchVisible: false,

      loading: false,
      tabKey: 1,
    };
    
  }
  getCustomerList = async(pageSize) => {
    this.setState({loading: true});
    const {access_token, client} = this.props;
    const {customerData, isTeam, sign, hasTeam, saleId} = this.state;
    const values = this.props.form.getFieldsValue();
    const res = await client.post( sign ? '/crm/api/mobile/customer/getCustomerBySalesid' : '/crm/api/mobile/customer/list',{
      access_token,
      isTeam,
      start: (pageSize - 1) * 20,
      length: 20,
      ...getNotEmptyObj(values),
      ...getNotEmptyObj({customer_type: sign ? 0 : null, searchSalesId: true ? saleId : null, customer_type: sign ? 0 : undefined}),
    });
    if(Number(res.status) === 0 && res.data && res.data.records){
      this.setState({
        customerData: pageSize === 1 ? res.data.records : [...customerData, ...res.data.records],
        loading: false,
        pageSize,
        total: res.data.pageCount,
      })
    }
  }

  searchCustomer = async (name) => {
    const {access_token, client} = this.props;
    const {searchPageSize, searchTotal} = this.state;
    const res = await client.post('/crm/api/mobile/customer/listForSearch', {
      name,
      start: (searchPageSize - 1) * 20,
      access_token,
    })
    if(Number(res.status) === 0){
      this.setState({
        searchPageSize: searchPageSize+1,
        searchTotal: res.data.pageCount,
        searchCustomerData: res.data.records,
      })
    }
  }

  ptr;
  getPtrNode = ref => {
    if (ref) {
      // console.log('getPtrNode', ReactDOM.findDOMNode(ref), ReactDOM.findDOMNode(ref).getBoundingClientRect());
      this.ptr = ref;
    }
  };

  onTabsChange = (tab, index) => {
    console.log(tab, index, Number(tab.value) === 2);
    this.props.form.resetFields();
    this.setState({
      customerData: [],
      sign: Number(tab.value) === 2,
      tabKey: tab.value,
      isTeam: 0,
      sidebar: Number(tab.value) === 2 ? this.renderFilterSigned() : this.renderFilterNotSigned(),
    }, () => {
      this.getCustomerList(1)
    });
  };

  renderFilterSigned = () => {
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        {getFieldDecorator('customerStatusForSearch', {
          rules: [
            {
              validator: (rules, value, callback) => {
                callback();
              }
            }
          ]
        })(<Select
          title="合作状态"
          data={[
            { label: '合作中', value: 1 },
            { label: '已到期', value: 2 },
          ]}
        />)}
        
        {getFieldDecorator('isSubmit', {
          rules: [
            {
              validator: (rules, value, callback) => {
                callback();
              }
            }
          ]
        })(<Select
          title="业务移交单"
          data={[
            { label: '已提交', value: 1 },
            { label: '未提交', value: 0 },
          ]}
        />)}
        
        {getFieldDecorator('elseWhereReportStatus', {
          rules: [
            {
              validator: (rules, value, callback) => {
                callback();
              }
            }
          ]
        })(<Select
          title="异地报备状态"
          data={[
            { label: '已报备', value: 1 },
            { label: '未报备', value: 0 },
          ]}
        />)}
        
        {getFieldDecorator('lastFollowUpTimeType', {
          rules: [
            {
              validator: (rules, value, callback) => {
                callback();
              }
            }
          ]
        })(<Select
          title="最近一次跟进时间"
          data={[
            { label: '昨天', value: 1 },
            { label: '今天', value: 2 },
            { label: '本周', value: 3 },
            { label: '上周', value: 4 },
            { label: '本月', value: 5 },
            { label: '上月', value: 6 },
          ]}
        />)}
        
        {getFieldDecorator('isActivate', {
          rules: [
            {
              validator: (rules, value, callback) => {
                callback();
              }
            }
          ]
        })(<Select
          title="激活状态"
          data={[
            { label: '已激活', value: 1 },
            { label: '未激活', value: 0 },
          ]}
        />)}

      </div>
    )
  }

  renderFilterNotSigned = () => {
    const {
      customerParameterSet,
      allProduct,
      // customerDemand,
      source,
    } = this.state;

    const {
      customerInsuredNumberDatas,
      customerLevelDatas,
      customerStaffSizeDatas,
    } = customerParameterSet;

    // const newCustomerInsuredNumberData = customerInsuredNumberDatas.map(item => ({label: item.parameterName, value: item.id}));
    // const newCustomerLevelData = customerLevelDatas.map(item => ({label: item.parameterName, value: item.id}));

    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        {getFieldDecorator('starLevel', {
          rules: [
            {
              validator: (rules, value, callback) => {
                console.log(value);
                callback();
              }
            }
          ]
        })(<Select
          title="重点客户"
          multiple
          data={[
            { label: <Star number={0} />, value: 0 },
            { label: <Star number={1} />, value: 1 },
            { label: <Star number={2} />, value: 2 },
            { label: <Star number={3} />, value: 3 },
            { label: <Star number={4} />, value: 4 },
            { label: <Star number={5} />, value: 5 }
          ]}
        />)}

        {getFieldDecorator('customerParamLevels', {
          initialValue: undefined,
          rules: [
            {
              validator: (rules, value, callback) => {
                console.log(value);
                callback();
              }
            }
          ]
        })(<Select
          title="客户等级"
          multiple
          data={getLabelValueData(customerLevelDatas)}
        />)}

        {getFieldDecorator('lastFollowUpTimeType', {
          initialValue: undefined,
          rules: [
            {
              validator: (rules, value, callback) => {
                console.log(value);
                callback();
              }
            }
          ]
        })(<Select
          title="最近一次跟进时间"
          data={[
            { label: '昨天', value: 1 },
            { label: '今天', value: 2 },
            { label: '本周', value: 3 },
            { label: '上周', value: 4 },
            { label: '本月', value: 5 },
            { label: '上月', value: 6 }
          ]}
        />)}

        {getFieldDecorator('nextFollowUpTimeType', {
          initialValue: undefined,
          rules: [
            {
              validator: (rules, value, callback) => {
                console.log(value);
                callback();
              }
            }
          ]
        })(<Select
          title="下次计划跟进时间"
          data={[{ label: '今天', value: 1 }, { label: '本周', value: 2 }, { label: '本月', value: 3 }]}
        />)}

        {getFieldDecorator('notFollowUpTimeType', {
          initialValue: undefined,
          rules: [
            {
              validator: (rules, value, callback) => {
                console.log(value);
                callback();
              }
            }
          ]
        })(<Select
          title="未跟进天数"
          data={[{ label: '1天', value: 1 }, { label: '2-15天', value: 2 }, { label: '15天以上', value: 3 }]}
        />)}

        {getFieldDecorator('isFollowUp', {
          initialValue: undefined,
          rules: [
            {
              validator: (rules, value, callback) => {
                console.log(value);
                callback();
              }
            }
          ]
        })(<Select title="是否跟进" data={[{ label: '已跟进', value: 1 }, { label: '未跟进', value: 2 }]} />)}

        {getFieldDecorator('followUpNumber', {
          initialValue: undefined,
          rules: [
            {
              validator: (rules, value, callback) => {
                console.log(value);
                callback();
              }
            }
          ]
        })(<Select
          title="已跟进次数"
          data={[
            { label: '0次', value: 1 },
            { label: '1-10次', value: 2 },
            { label: '11-20次', value: 3 },
            { label: '20次以上', value: 4 }
          ]}
        />)}

        {getFieldDecorator('customerSourceChannels', {
          initialValue: undefined,
          rules: [
            {
              validator: (rules, value, callback) => {
                console.log(value);
                callback();
              }
            }
          ]
        })(<Select
          title="客户获取方式"
          multiple
          data={[
            { label: '新增', value: 1 },
            { label: '转移', value: 2 },
            { label: '小公海认领', value: 3 },
            { label: '大公海认领', value: 4 },
            { label: '分配', value: 5 }
          ]}
        />)}

        {getFieldDecorator('insureStatus', {
          initialValue: undefined,
          rules: [
            {
              validator: (rules, value, callback) => {
                console.log(value);
                callback();
              }
            }
          ]
        })(<Select
          title="员工参保情况"
          multiple
          data={[
            { label: '自缴', value: 1 },
            { label: '代缴', value: 2 },
            { label: '未缴', value: 3 },
            { label: '其他', value: 4 }
          ]}
        />)}

        {getFieldDecorator('customerStaffSizes', {
          initialValue: undefined,
          rules: [
            {
              validator: (rules, value, callback) => {
                console.log(value);
                callback();
              }
            }
          ]
        })(<Select
          title="公司规模"
          multiple
          data={getLabelValueData(customerStaffSizeDatas)}
        />)}

        {getFieldDecorator('customerInsuredNumbers', {
          initialValue: undefined,
          rules: [
            {
              validator: (rules, value, callback) => {
                console.log(value);
                callback();
              }
            }
          ]
        })(<Select
          title="预计参保人数"
          multiple
          data={getLabelValueData(customerInsuredNumberDatas)}
        />)}

        {getFieldDecorator('cooperationIntention', {
          initialValue: undefined,
          rules: [
            {
              validator: (rules, value, callback) => {

                console.log(value);
                callback();
              }
            }
          ]
        })(<Select
          title="合作意向"
          multiple
          column={2}
          data={getLabelValueData(allProduct,'name')}
        />)}

        {getFieldDecorator('mobile', {
          rules: [
          ],
        })(<InputItem clear placeholder="点击填写">
          联系人手机号码
        </InputItem>)}

      </div>
    );
  };

  onOpenChange = (...args) => {
    // console.log(args);
    this.setState({ open: !this.state.open });
  };

  resetPtrHeight = () => {
    // console.log(this.ptr.offsetTop,document.documentElement.clientHeight, ReactDOM.findDOMNode(this.ptr).offsetTop)
    // const hei = document.documentElement.clientHeight - ReactDOM.findDOMNode(this.ptr).offsetTop;
    console.log(this.ptr.getBoundingClientRect());
    const hei = document.documentElement.clientHeight - this.ptr.offsetTop - 40;
    this.setState({
      height: hei
    });
  };

  getUserData = (data) => {
    let arr = [];
    data.map(item => {
      if(item.subDepartment && item.subDepartment.length > 0){
        arr = [...arr, ...this.getUserData(item.subDepartment)];
      }else if(item.employees && item.employees.length > 0){
        arr = [...arr, ...item.employees];
      }
    })
    return arr;
  }

  getUsers = async() => {
    const isTeam = await this.props.client.post('/crm/api/mobile/customer/isHaveTeamCustomerTab',{access_token: this.props.access_token});
    const res = await this.props.client.post('/crm/api/mobile/permission/getUserWithOrganization',{id: 666, access_token: this.props.access_token});
    const sales = this.getUserData(res.data);
    this.setState({
      hasTeam: Number(isTeam.data.isTeam) === 1,
      sales: getLabelValueData(sales, 'name'),
    })
  }

  onTeamChange = async(isTeam) => {
    this.props.form.resetFields();
    this.setState({ isTeam, }, () => {
      this.getCustomerList(1);
    })
  }

  getOptions = async() => {
    const [
      customerParameterSet,
      allProduct,
      // customerDemand,
      source,
    ] = await Promise.all([
      this.props.client.post('/crm/api/mobile/customerParameterSet/getSet', {access_token: this.props.access_token}),
      this.props.client.post('/crm/api/mobile/product/getAllEnableProduct', {access_token: this.props.access_token}),
      // this.props.client.post('/crm/api/mobile/customerDemand/getCustomerDemand', {access_token: this.props.access_token}),
      this.props.client.post('/crm/api/mobile/dictionary/getDataList', {access_token: this.props.access_token}),
    ]);
    this.setState({
      customerParameterSet: customerParameterSet.data,
      allProduct: allProduct.data,
      // customerDemand,
      source: source.data,
    }, () => {
      const sidebar = this.renderFilterNotSigned();
      this.setState({sidebar})
    });
  }

  renderBoxItem = (saleName) => {
    const {hasTeam} = this.state;
    const values = Object.values(getNotEmptyObj(this.props.form.getFieldsValue()));
    let hasValue = false;
    values.map(item => {
      if(Array.isArray(item) && item.length > 0){
        hasValue = true;
      }
      
      if(!Array.isArray(item) && item !== '' && item !== undefined && item !== null){
        hasValue = true;
      }
    })
    if(hasTeam){
      return [
  
        <Picker
          data={[{ label: '我的客户', value: 0 }, { label: '团队客户', value: 1 }]}
          value={[this.state.isTeam]}
          onChange={v => {this.onTeamChange(v[0])}}
          cols={1}
        >
          <div className="flex-box-center" style={{ height: '100%', width: '100%' }}>
            {this.state.isTeam === 1 ? '团队客户' : '我的客户'}
          </div>
        </Picker>,
  
        <Picker
          data={[{label: '全部', value: ''}, ...this.state.sales]}
          value={[this.state.saleId]}
          onChange={v => {
            this.setState({ saleId: v[0] }, () => {
              this.getCustomerList(1);
            });

          }}
          cols={1}
        >
          <div className="flex-box-center" style={{ height: '100%', width: '100%' }}>
            {saleName}
          </div>
        </Picker>,
  
        <div className="flex-box-center" style={{ height: '100%', width: '100%', color: hasValue ? '#3390FF' : '#666666' }} onClick={this.onOpenChange}>
          筛选
        </div>
  
      ]

    }else{
      return [

        <div className="flex-box-center" style={{ height: '100%', width: '100%' }}>
            我的客户
        </div>,

        <div className="flex-box-center" style={{ height: '100%', width: '100%', color: hasValue ? '#3390FF' : '#666666' }} onClick={this.onOpenChange}>
          筛选
        </div>
      ]
    }
  }

  componentWillMount() {
    
  }
  componentDidMount() {
    if (__CLIENT__) {
      setTimeout(async() => {
        this.resetPtrHeight();
        await this.getUsers();
        await this.getOptions();
        await this.getCustomerList(1);
      }, 0);
    }
    
  }

  render() {
    const { history } = this.props;
    const { customerData, sidebar, searchCustomerData, searchVisible } = this.state;
    const { getFieldDecorator } = this.props.form;
    console.log(searchCustomerData,'2')
    let saleName = this.state.sales.filter(item => Number(item.id) === Number(this.state.saleId));
    saleName = saleName.length > 0 ? saleName[0].name || '所属销售' : '所属销售';
    // console.log(saleName, this.state.saleId)

    return (
      <div className="customer-list-container">
      <Helmet title="客户列表" />
        <Loading visible={this.state.loading} />
        <AddCustomer visible ={false} />

        <Modal 
          search 
          visible={searchVisible} 
          onSubmit={this.searchCustomer}
          onCannel={() => {
            // this.searchCustomer('测试');
            this.setState({searchVisible: false})
          }}
        >
          <CList
            data={searchCustomerData}
            type={'search'}
            onClick={item => {
              this.setState({searchVisible: false},
                () => history.push({
                  pathname:'/customerDetails', 
                  state:{
                    id: item.id,
                  }
                })
              )
            }}
          />
        </Modal>
        <NavBar
          mode="dark"
          leftContent={
            <span
              onClick={() => {history.goBack()}}
            >
              <Icon key="0" type="left" style={{ verticalAlign: 'text-top' }} />返回
            </span>
          }
          rightContent={[
            <Icon onClick={() => {this.setState({searchVisible: true})}} key="0" type="search" style={{ marginRight: '16px' }} />,
            <i onClick={() => {this.props.history.push('/customer/add')}} key={1} style={{fontSize:'0.34rem'}} className='crmiconfont crmicon-jia'/>
          ]}
        >
          客户管理
        </NavBar>
        <WhiteSpace size="sm" />
        <Drawer
          key={this.state.tabKey}
          className="my-drawer"
          title="筛选"
          position="right"
          visible={this.state.open}
          onCannel={this.onOpenChange}
          clickTaskClose
          onOk={() => {this.getCustomerList(1)}}
          onReset={async() => {
            await this.props.form.resetFields();
            this.getCustomerList(1);
          }}
        >
          {sidebar}
        </Drawer>
        <Tabs
          tabs={this.state.tabs}
          renderTabBar={props => <Tabs.DefaultTabBar {...props} page={2} />}
          onChange={this.onTabsChange}
        >
          {/**
                    未签约客户
                */}
          <div>
            <RadioBox
              data={this.renderBoxItem(saleName)}
            />
          </div>

          {/**
                    已签约客户
                */}

          <div>
            <RadioBox
              data={this.renderBoxItem(saleName)}
            />
          </div>
        </Tabs>
        <WhiteSpace size="sm" />
        <div ref={this.getPtrNode} style={{ height: this.state.height || 'auto' }}>
          <PullToRefresh
            // ref={this.getPtrNode}
            direction="up"
            style={{
              height: '100%',
              overflow: 'auto'
            }}
            // damping={0}
            onRefresh={() => {
              const {pageSize, total} = this.state;
              if(pageSize < total){
                this.getCustomerList(pageSize+1);
              }
            }}
          >
            <CList
              data={customerData}
              type={this.state.sign ? 1 : 0}
              onClick={item => history.push({
                pathname:'/customerDetails', 
                state:{
                  id: this.state.sign ? item.id : item.customer.id,
                }
              })}
            />
          </PullToRefresh>
        </div>
      </div>
    );
  }
}
